
program ivclust 
version 9

/*2sls estimation with 2-way clustering with one endogenous variable*/

syntax anything [if] [in] [aweight fweight iweight pweight /], cluster(string) [*]

quietly {

tokenize `cluster'

xi:ivreg `anything' `if', cluster (`1')
gen numobs=e(N)
mat dd=e(b)
mat ddd=dd[1,1]
svmat ddd, names(coef)
mat vv=e(V)
mat vvv=vv[1,1]
svmat vvv, names(var)
matrix drop dd ddd vv vvv 
rename coef1 coef
rename var1 vara

xi:ivreg `anything' `if', cluster (`2') 
mat vv=e(V)
mat vvv=vv[1,1]
svmat vvv, names(var)
matrix drop vv vvv
rename var1 varb

xi:ivreg `anything' `if', cluster (`3') 
mat vv=e(V)
mat vvv=vv[1,1]
svmat vvv, names(var)
matrix drop vv vvv
rename var1 varc

gen truese=sqrt(vara+varb-varc)
drop vara varb varc 
}

rename coef cssa
rename truese truese_ssa

su numobs cssa truese_ssa
drop numobs cssa truese_ssa


end

 
